package util.bio.seq;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import util.bio.annotation.*;
import util.gen.*;
import util.bio.parsers.*;

/**Takes a UCSC gene table and a directory of xxx.fasta files and replaces the exonic sequence with Xs.*/
public class MaskExonsInFastaFiles {


	public static void main(String[] args) {
		//files
		File geneFile = new File ("/Users/nix/HCI/PIs/Thummel/flybasegenesApr04.xls");//args[0]);
		File fastaDir = new File ("/Users/nix/HCI/PIs/Thummel/RepeatMaskedFastas/");//args[1]);
		
		//parse gene table and split by chromosome, note keeping as end excluded
		UCSCGeneModelTableReader genes = new UCSCGeneModelTableReader(geneFile, 0);
		genes.splitByChromosome();
		HashMap chromSpecGenes = genes.getChromSpecificGeneLines();
		
		//for each chromosome
		Iterator it = chromSpecGenes.keySet().iterator();
		MultiFastaParser fastaParser = new MultiFastaParser();
		while (it.hasNext()){
			//get gene lines
			String chrom = (String) it.next();
			System.out.println("Processing "+chrom);
			UCSCGeneLine[] sub = (UCSCGeneLine[]) chromSpecGenes.get(chrom);
			
			//parse fasta and get sequence
			fastaParser.parseIt(new File (fastaDir, chrom+".fasta"));
			char[] seq = fastaParser.getSeqs()[0].toCharArray();
			
			//for each line, get exons
			for (int i=0; i< sub.length; i++){
				ExonIntron[] exons = sub[i].getExons();
				//for each exon, mask seq
				for (int j=0; j< exons.length; j++){
					//for each base, note end is excluded, interbase coordinates
					int start = exons[j].getStart();
					int stop = exons[j].getEnd();
					for (int k=start; k< stop; k++){
						seq[k] = 'X';
					}
				}
			}
			
			//write exon masked fasta
			File masked = new File (fastaDir, chrom+"_ExMsked.fasta");
			String fastaSeq = ">"+fastaParser.getNames()[0]+"\n"+new String(seq);
			IO.writeString(fastaSeq, masked);
		}


	}

}
